{% extends '_base.html' %}

{% block title %}{{ _('Sign In') }}{% endblock %}

{% block head %}

<style>
div.x-signin-panel {
	border-top-left-radius: 0;
	border-top-right-radius: 0;
	border-top: none;
}

div.x-oauth-signin-panel [class*=x-oauth-button-] {
	width: 240px;
	text-align: left;
}

div.x-oauth-signin-panel [class*=x-oauth-button-] i[class*=uk-icon-] {
	width: 20px;
}

[class*=x-oauth-button-],[class*=x-oauth-button-]:hover,[class*=x-oauth-button-]:focus,[class*=x-oauth-button-]:active {
	color: #fff;
	box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.05);
	text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.1);
}

[class*=x-oauth-button-]:hover,[class*=x-oauth-button-]:focus,[class*=x-oauth-button-]:active {
	filter: brightness(90%);
}

div.x-icon {
    display: block;
    float: left;
    margin-top: 12px;
    margin-right: 12px;
    width: 24px;
    height: 24px;
    background-repeat: no-repeat;
    background-position: center center;
}

</style>

<script>
function getWeb3Provider() {
    if (!window.web3Provider) {
        window.web3Provider = new ethers.providers.Web3Provider(window.ethereum, "any");
    }
    return window.web3Provider;
}

function ethAuth() {
	if (!ethereum.isMetaMask) {
		UIkit.modal.alert('MetaMask is not installed.');
		return;
	}
	doEthAuth().then(r => {
		console.log('eth sign ok');
		$('#ethForm input[name=message]').val(r.message);
		$('#ethForm input[name=signature]').val(r.signature);
		$('#ethForm').submit();
	}).catch(err => UIkit.modal.alert(translateError(err)));
}

function ethExpires() {
	let
		ts = parseInt('{{ __timestamp__ }}') + 604800000,
		d = new Date(ts),
		s = d.toISOString();
	return s.substring(0, 13) + ':00:00Z';
}

async function doEthAuth() {
	if (!window.ethCurrentAddress) {
		let accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
		if (accounts.length > 0) {
			window.ethCurrentAddress = accounts[0];
			console.log('set current address = ' + window.ethCurrentAddress);
		}
	}
	let message = 'Signin: {{ __host__ }}\r\nExpires: ' + ethExpires();
	let sign = await getWeb3Provider().getSigner().signMessage(message);
	return {
		message: message,
		signature: sign
	};
}

function passkeyAuth() {
	doPasskeyAuth().then(r => {
		console.log('passkey sign ok');
		location.assign(r.url);
	}).catch(err => {
		console.error(err);
	    UIkit.modal.alert(translateError(err))
	});
}

async function doPasskeyAuth() {
	const getResponse = await fetch(`/api/passkey/get/options?t=${Date.now()}`);
	const getOptions = await getResponse.json();
	console.log(getOptions);
	getOptions.challenge = base64_urlsafe_decode(getOptions.challenge);
	const cred = await navigator.credentials.get({
        publicKey: getOptions
    });
    const credential = {
        id: cred.id,
        type: cred.type,
        rawId: base64_urlsafe_encode(cred.rawId),
        response: {
            clientDataJSON: base64_urlsafe_encode(cred.response.clientDataJSON),
            authenticatorData: base64_urlsafe_encode(cred.response.authenticatorData),
            signature: base64_urlsafe_encode(cred.response.signature),
            userHandle: base64_urlsafe_encode(cred.response.userHandle)
        }
    };
    const signinResponse = await fetch('/api/passkey/signin', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(credential)
    });
    const signinResult = await signinResponse.json();
    if (!signinResponse.ok) {
        throw signinResult;
    }
    return signinResult;
}

function showTab(type) {
	$('#signin .x-tab').removeClass('uk-active');
	$('#signin .x-tab-' + type).addClass('uk-active');
	$('#signin .uk-panel').hide();
	$('#signin .x-panel-' + type).show();
}

function showOAuth() {
	showTab('oauth');
}

function showPasswordAuth() {
	showTab('passauth');
}

function showEthAuth() {
	showTab('ethauth');
}

function showPasskeyAuth() {
	showTab('passkeyauth');
}

function onPasswordAuth() {
	var
		email = $('#email').val().trim().toLowerCase(),
		pwd = $('#passwd').val();
	$('#hashPasswd').val(sha256.hmac(email, pwd));
	return true;
}

$(function () {
	{% if type == "oauth" %}
		showOAuth();
	{% elseif type == "passauth" %}
		showPasswordAuth();
	{% elseif type == "ethauth" %}
		showEthAuth();
	{% elseif type == "passkeyauth" %}
		showPasskeyAuth();
	{% endif %}

	if (!window.ethereum) {
		$('#signin .x-tab-ethauth').hide();
		$('#signin .x-panel-ethauth').hide();
	}

	if (!navigator.credentials) {
		$('#signin .x-tab-passkeyauth').hide();
		$('#signin .x-panel-passkeyauth').hide();
	}

	{% if error %}
		$('div.uk-alert-danger').show();
	{% endif %}
});

</script>
{% endblock %}

{% block content %}
	<div id="signin" style="width:480px; margin:0 auto;">
    	<ul id="x-tab" class="uk-tab">
    		{% if oauthEnabled %}
    		<li class="x-tab x-tab-oauth"><a href="#0" onclick="showOAuth()">OAuth</a></li>
    		{% endif %}
    		{% if passauthEnabled %}
    		<li class="x-tab x-tab-passauth"><a href="#0" onclick="showPasswordAuth()">Password</a></li>
    		{% endif %}
			{% if ethauthEnabled %}
    		<li class="x-tab x-tab-ethauth"><a href="#0" onclick="showEthAuth()">Web3</a></li>
    		{% endif %}
			{% if passkeyauthEnabled %}
    		<li class="x-tab x-tab-passkeyauth"><a href="#0" onclick="showPasskeyAuth()">Passkey</a></li>
    		{% endif %}
		</ul>

		<div style="display:none" class="x-panel-oauth uk-panel uk-panel-box uk-panel-box-secondary x-signin-panel x-oauth-signin-panel">
			<h3>Please signin without registration:</h3>

			{% for providerId in oauthConfigurations.keySet() %}
			{% set config = oauthConfigurations[providerId] %}
			<p>
				<button class="uk-button uk-button-large" style="text-align: left; width:280px" onclick="window.location.assign('/auth/from/{{ providerId }}')">
					<div class="x-icon" style="background-image: url(/static/img/icon/{{ providerId }}.svg);"></div>
					{{ _('Sign in with %1$s', config.name) }}
				</button>
			</p>
			{% endfor %}

		</div>

		<div style="display:none" class="x-panel-passauth uk-panel uk-panel-box uk-panel-box-secondary x-signin-panel x-password-signin-panel">
			<h3>Please signin with password:</h3>
        	<form method="post" action="/auth/signin/local" onsubmit="return onPasswordAuth()" class="uk-form uk-form-stack">
	            <div class="uk-alert uk-alert-danger" style="display:none">{{ _('Bad email or password.') }}</div>
	            <div class="uk-form-row">
	                <label class="uk-form-label" for="email">{{ _('Email') }}:</label>
	                <div class="uk-form-controls">
	                    <div class="uk-form-icon">
	                        <i class="uk-icon-envelope-o"></i>
	                        <input type="email" id="email" name="email" maxlength="50" style="width:300px" placeholder="email@example.com">
	                    </div>
	                </div>
	            </div>
	            <div class="uk-form-row">
	                <label class="uk-form-label" for="passwd">{{ _('Password') }}:</label>
	                <div class="uk-form-controls">
	                    <div class="uk-form-icon">
	                        <i class="uk-icon-lock"></i>
	                        <input type="password" id="passwd" maxlength="50" style="width:300px" placeholder="password">
	                        <input type="hidden" id="hashPasswd" name="passwd">
	                    </div>
	                </div>
	            </div>
	            <div class="uk-form-row">
	                <div class="uk-form-controls">
	                    <button type="submit" class="uk-button uk-button-primary"><i class="uk-icon-sign-in"></i> {{ _('Sign In') }}</button>
	                </div>
	            </div>
	        </form>
		</div>

		<div style="display:none" class="x-panel-passkeyauth uk-panel uk-panel-box uk-panel-box-secondary x-signin-panel x-passkeyauth-signin-panel">
			<h3>Please signin with Passkey:</h3>
			<p>
				<button class="uk-button uk-button-primary uk-button-large" onclick="passkeyAuth()">
					<i class="uk-icon-key"></i>
					{{ _('Sign in with %1$s', 'Passkey') }}
				</button>
			</p>
		</div>

		<div style="display:none" class="x-panel-ethauth uk-panel uk-panel-box uk-panel-box-secondary x-signin-panel x-ethauth-signin-panel">
			<h3>Please signin with Web3:</h3>
			<p>
				<button class="uk-button uk-button-large" onclick="ethAuth()">
					<div class="x-icon" style="background-image: url(/static/img/icon/metamask.svg);"></div>
					{{ _('Sign in with %1$s', 'MetaMask') }}
				</button>
			</p>
			<form id="ethForm" method="post" action="/auth/signin/eth" class="uk-hidden">
				<input type="hidden" name="message">
				<input type="hidden" name="signature">
			</form>
		</div>

    </div>
{% endblock %}
